package mo.offer_special;

import java.util.HashMap;
import java.util.Map;

public class L066 {

    private Trie root;
    private Map<String, Integer> key2val = new HashMap<>();

    /** Initialize your data structure here. */
    public L066() {
        this.root = new Trie();
    }

    public void insert(String key, int val) {
        //代码优化时主要if-else传参的变化
        int copy = val;
        //之前插入过
        if (key2val.containsKey(key)) {
            int lastVal = key2val.get(key);
            val = val - lastVal;
        }
        //执行插入逻辑
        insert(root, key, val);
        key2val.put(key, copy);
    }

    public int sum(String prefix) {
        Trie cur = root;
        for (char c : prefix.toCharArray()) {
            int idx = c - 'a';
            if (cur.children[idx] == null) {
                return 0;
            } else {
                cur = cur.children[idx];
            }
        }
        return cur.sum;
    }

    private void insert(Trie node, String key, int val) {
        Trie cur = node;
        for (char c : key.toCharArray()) {
            int idx = c - 'a';
            if (cur.children[idx] == null) {
                cur.children[idx] = new Trie(val);
            } else {
                cur.children[idx].sum += val;
            }
            cur = cur.children[idx];
        }
    }

    private static class Trie {
        public Trie[] children;
        public int sum;
        private boolean end;

        public Trie(int sum) {
            this.sum = sum;
            this.children = new Trie[26];
        }

        public Trie() {
            this.children = new Trie[26];
            this.sum = 0;
            this.end = false;
        }
    }

    public static void main(String[] args) {
        L066 test = new L066();
        test.insert("apple", 3);
        System.out.println(test.sum("ap"));
        test.insert("app", 2);
        System.out.println(test.sum("ap"));
        test.insert("apple", 5);
        test.insert("apple", 1);
        System.out.println(test.sum("apple"));
    }
}
